package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public void insert(UserInfo userInfo) {
        userInfoRepository.save(userInfo);
    }

    @Override
    public void delete(String id) {
        userInfoRepository.deleteById(id);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoRepository.save(userInfo);

    }

    @Override
    public UserInfo get(String id) {
        return userInfoRepository.findById(id).orElse(null);
    }

    @Override
    public List<UserInfo> list() {
        return userInfoRepository.findAll();
    }

    @Override
    public Boolean checkPhone(String phone) {
        UserInfo userInfo = userInfoRepository.findByPhone(phone);


        return userInfo != null;
    }

/*//从配置文件取短信的ur appkey
    @Value("${sms.url}")
    private String url;
    @Value("${sms.appkey}")
    private String appkey;*/
    public void sendVerifyCode(String phone) {
        //创建验证码
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
         //创建短信
        StringBuilder sb = new StringBuilder(80);
    sb.append("【凯信通】注册的短信验证码").append(code).append("必须在").append(Consts.VERIFY_CODE_VAI_TIME)
                .append("分钟内使用");
        //发送短信(模拟发送短信)
       System.out.println(sb);
       //真实发送短信：就是用java代码发起http请求
        //https://way.jd.com/chuangxin/dxjk?mobile=13568813957&content=【创信】你的验证码是：5873，3分钟内有效！&appkey=863a7d1fc309ec08b573eaa3aae0f9cf

        //RestTemplate封装了用于发送http请求的工具类
       /* String url="https://way.jd.com/kaixintong/kaixintong?mobile={1}&content={2}&appkey={3}";
        String appkey="863a7d1fc309ec08b573eaa3aae0f9cf";*/
       /* RestTemplate restTemplate = new RestTemplate();
        //getForObject方法：参数1：url 参数2：响应结果封装成对象的类型  参数3：请求携带的参数
        String ret = restTemplate.getForObject(url, String.class, phone, sb.toString(), appkey);
        System.out.println(ret);
        if (!ret.contains("SUCCESS")){
            throw new LogicException("短信发送失败");
        }
        System.out.println(ret);*/
        //把验证码存入redis中
        userInfoRedisService.sendVerifyCode(phone,code);

    }

    @Override
    public void regist(String nickname, String password, String rpassword, String phone, String verifyCode) {
        //验证传入的参数是否为空
        /*if (StringUtils.hasLength(phone)){
            throw new RuntimeException("手机号码不能为空");
        }*/
        AssertUtil.hasLength(nickname,"昵称不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        AssertUtil.hasLength(rpassword,"确认密码不能为空");
        AssertUtil.hasLength(phone,"手机号码不能为空");
        AssertUtil.hasLength(verifyCode,"验证码不能为空");
        //判断密码和确认密码是否一致
        AssertUtil.isEquals(password,rpassword,"密码确认有误");
        //手机号码必须唯一校验
        if (this.checkPhone(phone)){
            throw new LogicException("该手机号码存在了");
        }
        //手机号码格式必须正确
        String regex = "^1[3-9]\\d{9}$";
        if (phone.length() != 11) {
            throw new LogicException("手机号应为11位数");
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();

            if (!isMatch) {
                throw new LogicException("请填入正确的手机号");
            }
        }
            //短信验证码必须一致
        //从redis取出来的验证码和用户输入的验证码一致
        String code=userInfoRedisService.getVerifyCode(phone);
        AssertUtil.isEquals(verifyCode,code,"验证码失效或错误");
        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setEmail("");
      /* Md5Hash md5Hash = new Md5Hash(password);
        userInfo.setPassword(md5Hash.toString());//加密*/
        userInfo.setPassword(password);
       // UsernamePasswordToken token = new UsernamePasswordToken( phone,md5Hash.toString());
        //设置默认头像
        userInfo.setHeadImgUrl("images\\default.jpg");
        userInfo.setCity("");
        userInfo.setInfo("");
        //重要的状态设置默认值
        userInfo.setState(UserInfo.STATE_NORMAL);
      /*  //模拟系统异常
        throw  new IllegalArgumentException("SDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");*/
        userInfoRepository.save(userInfo);
    }

    @Override
    public UserInfo login(String username, String password) {
        //用username，password 到数据库查询有没有这个对象，user对象不为null则登录成功
        AssertUtil.hasLength(username,"用户名不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        UserInfo user= userInfoRepository.findByPhoneAndPassword(username,password);
        if (user==null){
            throw  new LogicException("用户名或密码错误");
        }
        return user;
    }

    @Override
    public List<UserInfo> queryCity(String city) {
        return userInfoRepository.findByCity(city);
    }
}
